import React, { useState } from 'react';
import api from './api/api';
import { Toast, ToastContainer } from 'react-bootstrap';
import { useHistory } from 'react-router-dom/cjs/react-router-dom.min';

const Signup = () => {
  const history = useHistory();
  const [nickname, setNickname] = useState('');
  const [username, setUsername] = useState('');
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [toastShow, setToastShow] = useState(false);
  const [toastContent, setToastContent] = useState('');

  const handleSignup = async () => {
    const body = { nickname, email, description: "", username, password };
    try {
      const response = await api.post('/users', body);
      setToastContent('注册成功!');
      setTimeout(() => {
        history.push('/login');
      }, 3000);
    } catch (error) {
      setToastContent(`注册失败: ${error.response.data.message}`);
    } finally {
      setToastShow(true);
    }
  };
  return (
    <div className='
        container
        min-h-100
        flex-fill'
    >
      <div className="container d-flex flex-column align-items-center">
        <h1 className='mt-2 mb-5'>注册</h1>
        <form onSubmit={(e) => e.preventDefault()}>
          <div className="mb-3">
            <label for="username" className="form-label">用户名</label>
            <input type="text" className="form-control" id="username" value={username} onChange={(e) => setUsername(e.target.value)} />
          </div>
          <div className="mb-3">
            <label for="nickname" className="form-label">昵称</label>
            <input type="text" className="form-control" id="nickname" value={nickname} onChange={(e) => setNickname(e.target.value)} />
          </div>
          <div className="mb-3">
            <label for="email" className="form-label">邮箱</label>
            <input type="text" className="form-control" id="email" value={email} onChange={(e) => setEmail(e.target.value)} />
          </div>
          <div className="mb-3">
            <label for="password" className="form-label">密码</label>
            <input type="password" className="form-control" id="password" value={password} onChange={(e) => setPassword(e.target.value)} />
          </div>
          <div className="text-center">
            <button type="submit" className="btn btn-primary" onClick={handleSignup}>提交</button>
          </div>
        </form>
      </div>
      <ToastContainer position='bottom-end' className='m-2'>
        <Toast show={toastShow} onClose={() => { setToastShow(false); }}>
          <Toast.Header>
            <img src="holder.js/20x20?text=%20" className="rounded me-2" alt="" />
            <strong className="me-auto">雨呓</strong>
          </Toast.Header>
          <Toast.Body>{toastContent}</Toast.Body>
        </Toast>
      </ToastContainer>
    </div>
  );
};

export default Signup;
